﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.CodeDom;
using System.Reflection;
using System.IO;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using Pic2Exe.Properties;
using System.Diagnostics;
namespace Pic2Exe
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            Convert();
        }

        private void Convert()
        {
            WriteSourceFile();
            File.Copy(this.tbFileName.Text.Trim(), "temp.jpg", true);

            CSharpCodeProvider provider = new CSharpCodeProvider();
            ICodeCompiler compiler = provider.CreateCompiler();

            CompilerParameters parameters = new CompilerParameters();
            parameters.IncludeDebugInformation=false;
            parameters.CompilerOptions="/platform:x86";
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            parameters.ReferencedAssemblies.Add("System.Drawing.dll");
            parameters.OutputAssembly=Path.ChangeExtension(this.tbFileName.Text,".exe");
            parameters.EmbeddedResources.Add("temp.jpg");
            parameters.GenerateExecutable=true;
            CompilerResults res= compiler.CompileAssemblyFromFile(parameters, "Pic2Exe.cs");
            if (res.Errors.Count == 0)
            {
                MessageBox.Show("Completed successfully");
            }
            else
            {
                MessageBox.Show("Conversion had some issues");
            }
            DeleteTempFiles();
        }

        private static void DeleteTempFiles()
        {
            File.Delete("Pic2Exe.cs");
            File.Delete("temp.jpg");
        }

        private void WriteSourceFile()
        {
            TextWriter writer = new StreamWriter("Pic2Exe.cs");
            writer.WriteLine(Resources.Pic2Exe);
            writer.Close();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            ShowOpenFileDialog();
        }

        private void ShowOpenFileDialog()
        {
            if (ofdBrowse.ShowDialog() == DialogResult.OK)
            {
                tbFileName.Text = ofdBrowse.FileName;
            }
        }
    }
   
}
